/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.controllers;

import com.entities.CompanyDenomination;
import com.entities.Credit;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.Stateless;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.persistence.Query;

/**
 *
 * @author ben
 */
@Stateless
public class CreditController {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    @PersistenceContext
    EntityManager em;
    private static final Logger logger = Logger.getLogger(Credit.class.getName());

    public Credit findById(Long id) {
        try {
            Credit credit = em.find(Credit.class, id);
            logger.log(Level.INFO, "Credit found {0}", credit.getId().toString());
            return credit;

        } catch (Exception e) {
            logger.log(Level.SEVERE, "Could not find Credit");
            return null;

        }

    }

    public List<Credit> getAllCredit() {
        try {
            Query findCompanyQuery = em.createNamedQuery("Credit.findAll");
            List<Credit> credits = findCompanyQuery.getResultList();
            System.out.println("Found list of credits");
            return credits;

        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }
    }
    
    public Credit getCreditByCompanyDenomination(CompanyDenomination companyDenomination)
    {
         try {
            return (Credit) em.createNamedQuery("Credit.findByCompanyDenomination").setParameter("companyDenomination", companyDenomination).setMaxResults(1).getSingleResult();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public Long saveCredit(Credit credit) {
        try {
            credit.setFileName("credit.png");
            BufferedImage i = createQRCode(credit.getPin());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(i, "png", baos);
            baos.flush();
            credit.setImage(baos.toByteArray());
            baos.close();
        
       // byte[] imageBytes = ((DataBufferByte) image.getData().getDataBuffer());
       
            em.persist(credit);
            em.flush();
            return credit.getId();



        } catch (Exception e) {

            return -1L;
        }
    }
      
    private BufferedImage createQRCode(String qrcodeData ) throws WriterException
    {
        try {
            String charset = "UTF-8";
            Map<EncodeHintType, ErrorCorrectionLevel> hintMap=
                    new HashMap<EncodeHintType, ErrorCorrectionLevel>();
            hintMap.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.L);
            BitMatrix matrix = new MultiFormatWriter().encode(new String(qrcodeData.getBytes(charset),charset), BarcodeFormat.QR_CODE, 200, 200, hintMap);
            
         
            
            return MatrixToImageWriter.toBufferedImage(matrix);
            
            
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(CreditController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (WriterException ex) {
            Logger.getLogger(CreditController.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }
}
